package fr.cpe.j2ee.projet.ejb;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.TypedQuery;

import fr.cpe.j2ee.projet.model.Conversation;
import fr.cpe.j2ee.projet.model.Employee;
import fr.cpe.j2ee.projet.model.EmployeesConversation;
import fr.cpe.j2ee.projet.model.EmployeesConversationPK;
import fr.cpe.j2ee.projet.model.Project;

/**
 * Session Bean implementation class ConversationSession
 */
@Stateless
@LocalBean
public class ConversationSession extends AbstractDAO<Conversation>
{
	@EJB
	private EmployeesConversationSession employeesConversationSession;
	
    /**
     * Default constructor. 
     */
    public ConversationSession()
    {
    	super(Conversation.class);
    }

    public Conversation create(Date startDate, Date endDate, Project project, HashMap<Employee, Boolean> participants) throws IllegalArgumentException
    {
    	if(project == null)
    	{
    		throw new IllegalArgumentException("Impossible de d�marrer une nouvelle conversation : le projet sp�cifi� n'existe pas !");
    	}
    	
    	System.out.println("projet : " + project + ", startDate : " + startDate + ", endDate : " + endDate);
    	Conversation conv = new Conversation();
    	conv.setConDayTimeBegin(startDate);
    	conv.setConDayTimeEnd(endDate);
    	conv.setProject(project);
    	
    	this.insert(conv);

    	for (Employee participant : participants.keySet())
    	{
    		EmployeesConversationPK ecPK = new EmployeesConversationPK();
    		ecPK.setConId(conv.getConId());
    		ecPK.setEmpId(participant.getEmpId());
    		
    		EmployeesConversation entry = new EmployeesConversation();
    		entry.setConversation(conv);
    		entry.setEmployee(participant);
    		entry.setEmpConCaller(participants.get(participant) ? (byte)1 : (byte)0);
    		entry.setId(ecPK);
    		employeesConversationSession.insert(entry);
			conv.addParticipant(entry);
    	}
    	
    	this.update(conv);
    	return conv;
    }
    
    public List<Conversation> findByEmployeeId(int employeeId) {
    	ArrayList<Object> parameters = new ArrayList<Object>();
    	parameters.add(employeeId);
    	TypedQuery<Conversation> query = this.buildSelectQuery(
    			"SELECT ec.conversation from EmployeesConversation ec "
    			+ "WHERE ec.employee.empId = ?1"
				, parameters);
		return query.getResultList();
    }
}
